﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wombat.Data.Model;
using Wombat.Data.Model.Dtos;

namespace Web.Models.Helpers
{
    public static class TagHelper
    {
        public static Tag GetTagById(WombatEntities db, int id)
        {
            var tag = db.Tags
                        .Include("Unit")
                        .FirstOrDefault(t => t.Id == id);
            return tag;
        }

        public static string GetParametersString(WombatEntities db, CodeTagDto codeTagDto)
        {
            return GetVariableAssignmentString(db, codeTagDto.InputParameters);
        }

        public static string GetVariableAssignmentString(WombatEntities db, IEnumerable<CodeTagAssignment> assignments)
        {
            var rv = new StringBuilder();
            foreach (var pTuple in assignments)
            {
                var tag = GetTagByGuid(db, pTuple.TagGuid);
                rv.AppendLine(string.Format("{0} <= {1} [{2}]", pTuple.VariableName, tag.Id, tag.Name));
            }
            return rv.ToString();
        }

        private static Tag GetTagByGuid(WombatEntities db, Guid tagGuid)
        {
            var tag = db.Tags.FirstOrDefault(t => t.Guid == tagGuid);
            if (tag != null)
                return tag;
            throw new InvalidOperationException(string.Format("Tag {0} not found.", tagGuid));
        }

        public static void CreateLink(WombatEntities db, Tag parent, Tag child, RelationshipType relationshipType)
        {
            var tagRel = new TagRelationship
                {
                    SourceTag = parent,
                    DestinationTag = child,
                    RelationshipType = (byte) relationshipType
                };
            db.AddToTagRelationships(tagRel);
        }

        public static IEnumerable<TagRelationship> GetLinksTo(WombatEntities db, long tagId, RelationshipType relationshipType)
        {
            return db.TagRelationships
                .Include("SourceTag")
                .Where(tr => tr.DestinationTagId == tagId && tr.RelationshipType == (byte) relationshipType)
                     .Select(t => t);
        }
    }
}